﻿using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace DllShepherd.SystemInternalTools
{
    class Program
    {
        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
        //[DllImport("user32.dll")]
        //private static extern int GetWindowModuleFileName(int hWnd, StringBuilder title, int size);
        [DllImport("user32.dll")]
        static extern int GetWindowTextLength(IntPtr hWnd);
        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
        [DllImport("psapi.dll")]
        private static extern uint GetModuleFileNameEx(IntPtr hWnd, IntPtr hModule, StringBuilder lpFileName, int nSize);
        [DllImport("kernel32.dll")]
        private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
        [DllImport("user32.dll")]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);

        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr handle);

        static void Main(string[] args)
        {
            var window = GetTopWindowText();
            Console.WriteLine(DateTime.Now + ":" + window);

            while(true)
            {
                var temp = GetTopWindowText();
                if(temp != window)
                {
                    Console.WriteLine(DateTime.Now + ":" + temp);

                    window = temp;
                }
                Thread.Sleep(500);
            }
        }

        public static string GetTopWindowText()
        {
            var hWnd = GetForegroundWindow();
            var length = GetWindowTextLength(hWnd);
            var text = new StringBuilder(length + 1);
            GetWindowText(hWnd, text, text.Capacity);
            return GetTopWindowName() + " -> " + text;
        }

        public static string GetTopWindowName()
        {
            var hWnd = GetForegroundWindow();
            uint lpdwProcessId;
            GetWindowThreadProcessId(hWnd, out lpdwProcessId);

            var hProcess = OpenProcess(0x0410, false, lpdwProcessId);

            var text = new StringBuilder(1000);
            GetModuleFileNameEx(hProcess, IntPtr.Zero, text, text.Capacity);

            CloseHandle(hProcess);

            return text.ToString();
        }
    }
}
